package de.bildung.koblenz.adapter;

import java.io.IOException;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;
import de.bildung.koblenz.dialogs.EditSocketDialog;
import de.bildung.koblenz.dialogs.EditSocketDialog.IEditSocketResult;
import de.bildung.koblenz.homeswitch.R;
import de.bildung.koblenz.homeswitch.entities.Socket;
import de.bildung.koblenz.network.SocketUtil;

public class SocketListItemAdapter extends ArrayAdapter<Socket> {
	
	private SocketUtil socketUtil;

	public SocketListItemAdapter(Context context, SocketUtil util) {
		super(context, R.layout.list_item_socket);
		this.socketUtil = util;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final Socket socketItem = getItem(position);
		LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		convertView = inflater.inflate(R.layout.list_item_socket, parent, false);
		final TextView textView = (TextView) convertView.findViewById(R.id.list_item_socket_name);
		final Switch socket = (Switch) convertView.findViewById(R.id.switch1);
		textView.setText(socketItem.getName());
		convertView.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				final EditSocketDialog dialog = new EditSocketDialog(getContext(), new IEditSocketResult() {
					
					@Override
					public void finish(boolean edited, Socket socket) {
						if (edited) {
							if (socket != null) {
								textView.setText(socket.getName());
							} else {
								remove(socketItem);
							}
						}
					}
				});
				dialog.setSocket(socketItem);
				dialog.show();
				return false;
			}
		});
		socket.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				try {
					socketUtil.turnSwitchOnOff(socketItem.getId(), isChecked);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		return convertView;
	}
	
	

}
